Exercises - Objects

Using an object

Below is the definition of an object. Run the cell and create at least two instances of it.


In [ ]:
class Car(object):
    
    def __init__(self, make, model, year, mpg=25, tank_capacity=30.0, miles=0):
        self.make = make
        self.model = model
        self.year = year
        self.mpg = mpg
        self.gallons_in_tank = tank_capacity # cars start with a full tank
        self.tank_capacity = tank_capacity
        self.miles = miles
        
    def __str__(self):
        return "{} {} ({}), {} miles and {} gallons in tank".format(self.make, 
                                                                    self.model, 
                                                                    self.year, 
                                                                    self.miles, 
                                                                    self.gallons_in_tank)
    
    def drive(self, new_miles):
        """Drive the car X miles and return number of miles driven.
        If there is not enough fuel, drive 0 miles."""
        fuel_need = new_miles/self.mpg
        if fuel_need <= self.gallons_in_tank:
            self.miles = self.miles + new_miles
            self.gallons_in_tank = self.gallons_in_tank - fuel_need
            return new_miles
        else:
            raise ValueError("Would run out of gas!")
            
    def fill_up(self):
        self.gallons_in_tank = self.tank_capacity

In [ ]:
volvo = Car("Volvo", "S40", "2017", 25, 40, 0)
print(volvo)

Simple modification to class

OK, our car has a major problem: it can't be filled up.

Add a method called fill_up() to your class. It is up to you if you want to enable filling by an arbitary number or only back to the full state.

If you allow arbitary amounts of liquid remember to consider overfilling the tank.

Once you edit your class, the old objects do not automatically adopt to the changes you made. You will need to re-create them.

Exceptions

Now make a modification to the drive-method: if an attempt is made to drive more than the gas will allow, create and raise an exception.

Instead of creating your own exception you may use a ValueError for this case, as it is a logical choice.

Now add a try-except clause to the following:


In [ ]:
try:
    suv = Car("Ford", "Escape", 2017, mpg=18, tank_capacity=30)
    suv.drive(600)
except ValueError:
    print("Can't drive that far")